//回到顶部
const returnUp=document.querySelector('#return')

function outputTop() {    
    let i = document.documentElement.scrollTop
    let timer = setInterval(function () {
        i=i-20
        if (i <= 0) {
            clearInterval(timer)
        }
        document.documentElement.scrollTop = i
    }, 1)
}     

window.onscroll = function () {    
    console.log('浏览器');
    let i = document.documentElement.scrollTop
    console.log(i);
    if (i <= 0) {
        returnUp.style.display ='none'
    } else {
        returnUp.style.display ='block'
        //$('#return').css('display','block')        
    }
}

//获取商品id
function getProductId() {
    //http://127.0.0.1:5500/code/detail.html?id=4055442  通过url链接的裁切
    let url = location.href
    let params = url.substring(url.indexOf('?') + 1)//从？后一位开始剪切
    let arr = params.split('=')//得到的内容再从等号分割得到数组
    let id = arr[1]
    return id //返回数组下标为1的内容，就是id
}

console.log(getProductId());//得到id

function getProductDetail() {
    let id = getProductId()//调用id
    $.ajax({
        url: 'http://www.xiongmaoyouxuan.com/api/detail',
        type: 'get',
        data: {
            id
        },
        success: function (res) {
            showProductDetail(res.data)//用函数形式传参渲染输出
        }
    })
}

function showProductDetail(data) {
    let id = getProductId()//调用id
    let str = `
    <div class="top clearfix">
        <div class="g-left fl">
            <div class="m-show">
                <div class='imgBox'><img src="${data.share.imageUrl}" alt=""></div>
                <div class="block"></div>
                <div class="big"><img src="${data.share.imageUrl}" alt="" class="right-img"></div>            
            </div>
            <ul class="m-choose clearfix">
            <li><img src="${data.detail.photo[0].url}" width="60px" alt="1"></li>
            <li><img src="${data.detail.photo[1].url}" width="60px" alt="2"></li>
            <li><img src="${data.detail.photo[2].url}" width="60px" alt="3"></li>
            <li><img src="${data.detail.photo[3].url}" width="60px" alt="4"></li>
            </ul>
        </div>

        <div class="g-right fl clearfix">
            <h2>${data.share.title}</h2>
            <p>${data.share.text}</p>
            <div class="info">
                <p>${data.shop.shopScoreText}</p>
                <p>${data.shop.title}</p>
                <p>预售时间: ${data.shop.createTime}</p>
            </div>
            <p class="price">折扣价&emsp;￥${data.detail.originPrice}</p>
            <br>
            <br>
            <button class="cart-add">加入购物车</button>
        </div>
    </div>
    <div class="bottom">
        <ul class="bottomUl clearfix">
            <li><img src="${data.detail.photo[0].url}" width="60px" alt="1"></li>
            <li><img src="${data.detail.photo[1].url}" width="60px" alt="2"></li>
            <li><img src="${data.detail.photo[2].url}" width="60px" alt="3"></li>
            <li><img src="${data.detail.photo[3].url}" width="60px" alt="4"></li>
        </ul>
    </div>
    `
    $('#detail').html(str)  
    
    $('ul').on('click', 'img', function () {
        let num = $(this).prop('alt')
        num=num-1
        $('.imgBox>img').prop('src', `${data.detail.photo[num].url}`)
        $('.big>img').prop('src', `${data.detail.photo[num].url}`)
    })

    $('.cart-add').on('click', function () {//加入购物车的点击事件
        
        let newproduct = {
            id:id,
            name: data.share.title,
            url: data.share.imageUrl,
            price: data.detail.originPrice,
            num:1,
            singlePrice:data.detail.originPrice,
            state:false
        } 
            let cartListStr = localStorage.getItem('NEWCARTLIST')//读取整个数组，但是储存进去是字符串
            let cartArray = JSON.parse(cartListStr) || []//将字符串转成数组，第一次读取不到，赋值为空

        
            var cartArrayId=cartArray.some(function (item) {//首先判断这个新加入的数组是否存在，并接受返回的布尔值
                return item.id==newproduct.id
            })
        console.log(cartArrayId);     
        
        if (cartArrayId) {//如果存在
            let newcartArray=cartArray.find(item=>item.id==newproduct.id)//那么找到存在的这条数据并且让数字加加
            console.log(newcartArray);
            newcartArray.num++

            let yesOrNo = confirm('商品数量+1')
            if (yesOrNo) {
                location.href="./cart.html"
            }

            //同时我还想改变价格

            newcartArray.singlePrice = Number(newcartArray.num * newcartArray.price).toFixed(2)
            console.log(newcartArray.singlePrice);//计算单品总价 

            localStorage.setItem('NEWCARTLIST', JSON.stringify(cartArray))//再次将得到的新数组转成字符串储存
            
        } else {
            cartArray.push(newproduct)//如果不存在则直接将元素添加到数组后面
            localStorage.setItem('NEWCARTLIST', JSON.stringify(cartArray))//再次将得到的新数组转成字符串储存
            let yesOrNo = confirm('添加成功')
            if (yesOrNo) {
                location.href="./cart.html"
            }
        }
    })

   openBig()
}

function openBig() {
    let glassBoxw = $('.big').css('width') //放大区域
    let showBoxw = $('.imgBox').css('width')//显示普通图片的盒子
    let maskw= $('.block').css('width')//遮罩层
    let bgw = parseInt(glassBoxw) * parseInt(showBoxw) / parseInt(maskw)
   //计算高
    let glassBoxh = $('.big').css('width') //放大区域
    let showBoxh = $('.imgBox').css('width')//显示普通图片的盒子
    let maskh= $('.block').css('width')//遮罩层
    let bgh = parseInt(glassBoxh) * parseInt(showBoxh) / parseInt(maskh)

    $('.right-img').css('width',`${bgw}px`)//计算图片大小
    $('.right-img').css('height', `${bgh}px`)



    $('.imgBox').on('mousemove', function (e) {//移入显示和移动
        e = e || window.event
        $('.big').css('display', 'block')
        $('.block').css('display', 'block')

        let x = e.offsetX - $('.block').width() / 2//找到光标位置
        let y = e.offsetY - $('.block').height() / 2
        
        if(x<0)x=0//边界问题
        if(y<0)y=0
        if(x>$('.imgBox').width()-$('.block').width())x=$('.imgBox').width()-$('.block').width()
        if(y>$('.imgBox').height()-$('.block').height())y=$('.imgBox').height()-$('.block').height()

        $('.block').css({//遮罩层移动
            top: y+'px',
            left: x+'px'
        })
        console.log(x,y);

        let movex=x*parseInt(glassBoxw)/parseInt(maskw)//计算移动距离
        let movey=y*parseInt(glassBoxh)/parseInt(maskh)
         
        $('.right-img').css('top',`${-movey}px`)//赋值
        $('.right-img').css('left', `${-movex}px`)
    })

    $('.imgBox').on('mouseout', function () {//移除显示
        $('.big').css('display', 'none')
        $('.block').css('display', 'none')
    })
}



getProductDetail()